package org.god.core;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class SqlSession {
    private SqlSessionFactory sqlSessionFactory;

    public SqlSession(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    public void insert(String sql,Object pojo) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, SQLException {
        //获取sql语句   insert into t_car
        //        (id,car_num,brand,guide_price,produce_time,car_type)
        //        values
        //        (null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})
        Connection connection = sqlSessionFactory.getTransaction().getConnection();
        String sqlsatte = sqlSessionFactory.getMappedStatement().get(sql).getSql();
        //替换？
        String resql=sqlsatte.replaceAll("#\\{[0-9a-zA-Z_$]*\\}", "?");
        PreparedStatement pc = connection.prepareStatement(resql);

        //#索引qi
        int fromindex=0;
        //问号的位置
        int index=1;
        while (true){
            int indexjin= sqlsatte.indexOf("#",fromindex);
            if(indexjin<0){
                break;
            }
            int indexyou= sqlsatte.indexOf("}",indexjin);
            fromindex=indexyou+1;
            //获取属性名
            String attName = sqlsatte.substring(indexjin + 2, indexyou);
            //获取get方法和属性值
            String getMethodName="get"+attName.toUpperCase().charAt(0)+attName.substring(1);
            Method method = pojo.getClass().getDeclaredMethod(getMethodName);
            Object value = method.invoke(pojo);
            pc.setString(index,value.toString());
            index++;
        }
        //执行sql
        int i = pc.executeUpdate();
        System.out.println("受影响的行数"+i);

    }

    public void commit(){
        sqlSessionFactory.getTransaction().commit();
    }
    void rollback(){
        sqlSessionFactory.getTransaction().rollback();
    }

    public void close() {
        sqlSessionFactory.getTransaction().close();
    }


}
